<template>
  <div class="news-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>新闻管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索新闻标题..."
              style="width: 200px; margin-right: 16px"
              clearable
              @input="handleSearch"
            />
            <el-button type="primary" @click="handleAdd">添加新闻</el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredNews" style="width: 100%" v-loading="loading">
        <el-table-column prop="newsId" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="标题" min-width="250" show-overflow-tooltip />
        <el-table-column prop="type" label="分类" width="120" align="center">
          <template #default="scope">
            <el-tag>{{ getArticleType(scope.row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="180" align="center" />
        <el-table-column prop="views" label="浏览量" width="100" align="center">
          <template #default="scope">
            <el-tag type="info" effect="plain">{{ scope.row.views || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button size="small" type="primary" plain @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-popconfirm
                title="确定要删除该新闻吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="handleDelete(scope.row)"
              >
                <template #reference>
                  <el-button size="small" type="danger" plain>删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑新闻对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加新闻' : '编辑新闻'"
      width="70%"
      destroy-on-close
    >
      <el-form 
        ref="newsFormRef"
        :model="newsForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="newsForm.title" placeholder="请输入新闻标题" />
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <el-select v-model="newsForm.type" placeholder="请选择新闻分类" style="width: 100%">
            <el-option label="健康资讯" value="健康" />
            <el-option label="养生知识" value="文章" />
            <el-option label="专家观点" value="专家" />
            <el-option label="活动公告" value="活动" />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <el-input v-model="newsForm.coverImage" placeholder="请输入封面图片URL" />
          <div class="image-preview" v-if="newsForm.coverImage">
            <img 
              :src="newsForm.coverImage" 
              alt="封面预览"
              @click="handleImagePreview(newsForm.coverImage)"
              style="cursor: pointer"
            />
          </div>
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input 
            v-model="newsForm.summary" 
            type="textarea" 
            :rows="3"
            placeholder="请输入新闻摘要"
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="newsForm.content" 
            type="textarea" 
            :rows="10"
            placeholder="请输入新闻内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加图片预览对话框 -->
    <el-dialog v-model="showImagePreview" title="图片预览" width="50%">
      <img :src="previewImage" style="width: 100%; max-height: 70vh; object-fit: contain;" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getNewsList, addNews, updateNews, deleteNews } from '@/api/news'

// 状态变量
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const news = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const newsForm = ref({})
const newsFormRef = ref(null)

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入新闻标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度应在2-100个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择新闻分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入新闻内容', trigger: 'blur' },
    { min: 10, message: '内容不能少于10个字符', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入新闻摘要', trigger: 'blur' },
    { min: 10, max: 200, message: '摘要长度应在10-200个字符之间', trigger: 'blur' }
  ],
  coverImage: [
    { required: true, message: '请输入封面图片URL', trigger: 'blur' },
    { pattern: /^(http|https):\/\/[^ "]+$/, message: '请输入有效的图片URL', trigger: 'blur' }
  ]
}

// 获取文章类型显示文本
const getArticleType = (type) => {
  const types = {
    '健康': '健康资讯',
    '文章': '养生知识',
    '专家': '专家观点',
    '活动': '活动公告'
  }
  return types[type] || type
}

// 过滤新闻列表
const filteredNews = computed(() => {
  if (!searchQuery.value) return news.value
  const query = searchQuery.value.toLowerCase()
  return news.value.filter(item => 
    item.title?.toLowerCase().includes(query)
  )
})

// 获取新闻列表
const fetchNews = async () => {
  loading.value = true
  try {
    const response = await getNewsList({
      page: currentPage.value,
      size: pageSize.value
    })
    console.log('新闻数据:', response)
    if (response.data && response.data.list) {
      news.value = response.data.list.map(item => ({
        ...item,
        publishTime: item.publishTime ? formatDate(new Date(item.publishTime)) : ''
      }))
      total.value = response.data.total
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error)
    ElMessage.error('获取新闻列表失败')
  } finally {
    loading.value = false
  }
}

// 处理添加
const handleAdd = () => {
  dialogType.value = 'add'
  newsForm.value = {
    title: '',
    type: '',
    coverImage: '',
    summary: '',
    content: '',
    views: 0,
    publishTime: formatDate(new Date())
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  newsForm.value = {
    newsId: row.newsId,
    title: row.title,
    type: row.type,
    content: row.content,
    summary: row.summary,
    coverImage: row.coverImage,
    views: row.views,
    publishTime: row.publishTime
  }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (row) => {
  try {
    const response = await deleteNews(row.newsId)
    if (response === true || response.code === 200) {
      ElMessage.success('删除成功')
      fetchNews()
    } else {
      if (response) {
        ElMessage.success('删除成功')
        fetchNews()
      } else {
        ElMessage.error('删除失败')
      }
    }
  } catch (error) {
    console.error('删除新闻失败：', error)
    ElMessage.error('删除失败')
  }
}

// 处理表单提交
const handleSubmit = () => {
  newsFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          ...newsForm.value,
          publishTime: newsForm.value.publishTime 
            ? formatDate(new Date(newsForm.value.publishTime))
            : formatDate(new Date()),
          status: '已发布',
          type: newsForm.value.type,
                    authorId: 1,
          articleType: 'health'
        }

        // 如果是添加操作,删除不需要的字段
        if (dialogType.value === 'add') {
          delete submitData.newsId
          delete submitData.views
        }

        const api = dialogType.value === 'add' ? addNews : updateNews
        const response = await api(submitData)
        
        if (response === true || response.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          fetchNews() // 刷新列表
        } else {
          if (response) {
            ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
            dialogVisible.value = false
            fetchNews() // 刷新列表
          } else {
            ElMessage.error('操作失败')
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchNews()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchNews()
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchNews()
}

// 添加图片预览功能
const previewImage = ref(null)
const showImagePreview = ref(false)

const handleImagePreview = (url) => {
  previewImage.value = url
  showImagePreview.value = true
}

// 日期格式化方法
const formatDate = (date) => {
  const d = new Date(date)
  const pad = (num) => String(num).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

onMounted(() => {
  fetchNews()
})
</script>

<style scoped>
.news-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.image-preview {
  margin-top: 10px;
  width: 200px;
  height: 150px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

:deep(.el-dialog__body) {
  padding: 20px 40px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}

:deep(.el-form-item__content) {
  width: calc(100% - 100px);
}
</style>